package guoanmaker.operator.helper.common.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import com.aliyun.oss.OSSClient; 

/**
 * 
* @ClassName: FileConvertImageUtil 
* @Description: TODO(文件转换为Image工具类) 
* @author (ZhangXinYu)  
* @date 2018年1月16日 上午10:42:50 
* @version V1.0
 */
public class FileConvertImageUtil
{
    
    public static void main(String[] args)throws Exception {  
        //long start = System.currentTimeMillis();  
        /*String filepath = "D:/blank.signed.pdf";  
        PDDocument document = new PDDocument();  
        File pdfFile = new File(filepath);  
        document = PDDocument.load(pdfFile, (String)null);  
        int size = document.getNumberOfPages();  
        List<BufferedImage> piclist = new ArrayList();   
        for(int i=0 ; i < size; i++){  
            BufferedImage  image = new PDFRenderer(document).renderImageWithDPI(i,130,ImageType.RGB);  
            piclist.add(image);  
        }  
        document.close();*/  
        //yPic(piclist,"D:/blank.signed.png");  
       /* FileOutputStream out = new FileOutputStream("D:/Users/ex-wangyide001/workspace/testsrc/yanglaoxian/PDFBox-"+i+".jpg"); 
        ImageIO.write(image, "jpg", out); 
        out.close();*/  
        //long end = System.currentTimeMillis();  
        //System.out.println(end-start); 
    	
    	System.out.println(getPDFImg("https://guoanchuangke2.oss-cn-beijing.aliyuncs.com/datas/contractFile/1516082055407.signed.pdf?Expires=4669681285&OSSAccessKeyId=LTAILWi7cyx4nHeI&Signature=niANwaf5EZmvMg8GIuzhEA2IW5s%3D"));
    }  
    
    /**
     * 通过URL读取OSS上的PDF文件  将文件转换为图片 上传到OSS中  返回图片路径
     * 
     */
    @SuppressWarnings({ "unchecked", "rawtypes", "resource" })
	public static String getPDFImg(String urlPath){
    	String resultPath = "";
    	if(urlPath == null || urlPath.equals("")){
    		return "";
    	}
    	//通过URL获取文件
    	try{
    		URL url = null;
    		url = new URL(urlPath);
    		HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
			
			PDDocument document = new PDDocument();  
	        document = PDDocument.load(is, (String)null);  
	        int size = document.getNumberOfPages();  
	        List<BufferedImage> piclist = new ArrayList();   
	        for(int i=0 ; i < size; i++){  
	            BufferedImage  image = new PDFRenderer(document).renderImageWithDPI(i,130,ImageType.RGB);  
	            piclist.add(image);  
	        }  
	        document.close();  
	        resultPath = yPic(piclist);
    	}catch (Exception e) {
    		e.printStackTrace();
		}
		
    	return resultPath;
    }
    
    /** 
     * 将宽度相同的图片，竖向追加在一起 ##注意：宽度必须相同 
     *  
     * @param piclist 
     *            文件流数组 
     * @param outPath 
     *            输出路径 
     */  
    @SuppressWarnings("unused")
	public static String yPic(List<BufferedImage> piclist) {// 纵向处理图片
    	String resultPath = "";
        if (piclist == null || piclist.size() <= 0) {  
            System.out.println("图片数组为空!");  
            return resultPath;  
        }  
        try {  
            int height = 0, // 总高度  
            width = 0, // 总宽度  
            _height = 0, // 临时的高度 , 或保存偏移高度  
            __height = 0, // 临时的高度，主要保存每个高度  
            picNum = piclist.size();// 图片的数量  
            File fileImg = null; // 保存读取出的图片  
            int[] heightArray = new int[picNum]; // 保存每个文件的高度  
            BufferedImage buffer = null; // 保存图片流  
            List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB  
            int[] _imgRGB; // 保存一张图片中的RGB数据  
            for (int i = 0; i < picNum; i++) {  
                buffer = piclist.get(i);  
                heightArray[i] = _height = buffer.getHeight();// 图片高度  
                if (i == 0) {  
                    width = buffer.getWidth();// 图片宽度  
                }  
                height += _height; // 获取总高度  
                _imgRGB = new int[width * _height];// 从图片中读取RGB  
                _imgRGB = buffer  
                        .getRGB(0, 0, width, _height, _imgRGB, 0, width);  
                imgRGB.add(_imgRGB);  
            }  
            _height = 0; // 设置偏移高度为0  
            // 生成新图片  
            BufferedImage imageResult = new BufferedImage(width, height,  
                    BufferedImage.TYPE_INT_BGR);  
            for (int i = 0; i < picNum; i++) {  
                __height = heightArray[i];  
                if (i != 0)  
                    _height += __height; // 计算偏移高度  
                imageResult.setRGB(0, _height, width, __height, imgRGB.get(i),  
                        0, width); // 写入流中  
            }  
            
            /*利用bufferedImage  将pdf生成图片上传到OSS中 */
            resultPath = uploadImageFile( imageResult);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return resultPath;
    }  
    
    /**
     * 通过BufferedImage 上传图片到OSS中  返回图片路径
     */
    @SuppressWarnings("unused")
	public static String uploadImageFile(BufferedImage image){
    	OSSUnitHelper ossunit=new OSSUnitHelper();
		OSSClient client=OSSUnitHelper.getOSSClient();
		String diskName = "datas/contractImg/";
		/*String fileName = new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000)
				+ contractlogo.getOriginalFilename().substring(contractlogo.getOriginalFilename().indexOf("."));
        String md5key = OSSUnitHelper.uploadObject2OSS(client, contractlogo, diskName,fileName);*/
		String fileName = new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000) + ".png";
		//BufferedImage 转 InputStream
		ByteArrayOutputStream bs =new ByteArrayOutputStream();
		ImageOutputStream imOut;
		try {
			imOut = ImageIO.createImageOutputStream(bs);
			ImageIO.write(image,"jpg",imOut); //scaledImage1为BufferedImage，jpg为图像的类型
		} catch (IOException e) {
			e.printStackTrace();
		}
		InputStream is =new ByteArrayInputStream(bs.toByteArray());
		//使用InputStream  上传图片
		String md5key = OSSUnitHelper.uploadFile2OSS(client, is, fileName, diskName);
        String url="";
        url=OSSUnitHelper.getUrl(client, diskName, fileName);
        String urll=    url.substring(4, url.length());
        url="https"+urll;
        //System.out.println(url+"5");
        return url;
    }
    
}

